package com.larry;

import java.util.Arrays;
import java.util.HashMap;

/**
 * @ProjectName algorithm
 * @Author larry
 * @Date 14:06 2021/7/23
 * @Description 两数之和
 **/
public class TwoSum {

    //方法一：暴力法   时间复杂度O(n²)
    public static int[] test(int[] nums,int target){
        int n = nums.length;
        //双重循环
        for (int i = 0; i < n - 1; i++) {
            for (int j = i + 1 ; j < n; j++) {
                if (nums[i] + nums[j] == target){
                    return new int[]{i,j};
                }
            }
        }
        return null;
    }

    //方法二：hash表     时间复杂度O(n)
    public static int[] testHash(int[] nums,int target){
        int n = nums.length;
        HashMap<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < n; i++) {
            map.put(nums[i],i);
        }

        for (int i = 0; i < n; i++) {
            int num = target - nums[i];
            if (map.containsKey(nums[i]) && map.get(num) != i){
                return new int[]{i,map.get(num)};
            }
        }
        return null;
    }

    //方法三：hash表     时间复杂度O(n)
    public static int[] testHash2(int[] nums,int target){
        int n = nums.length;
        HashMap<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < n; i++) {
            int num = target - nums[i];
            if (map.containsKey(num)){
                return new int[]{i,map.get(num)};
            }
            map.put(nums[i],i);
        }
        return null;
    }

    public static void main(String[] args) {
        int[] input = {2,7,11,15};
        int target = 9;

        int[] test = TwoSum.testHash2(input, target);
        System.out.println(Arrays.toString(test));
    }
}
